<template>
  <div class="execution">
      <el-button-group style="margin-bottom: 10px;">
        <el-button type="primary" icon="el-icon-search" @click="searchHandle">查询</el-button>
        <el-button type="primary" icon="el-icon-delete" @click="searchReset">清空</el-button>
        <el-button v-if="userInfo.roleType&&userInfo.roleType.includes(',ROLE_ADMIN,')" size="mini" icon="el-icon-plus" type="primary"   @click="syncSchool()">同步</el-button>
        <el-button v-if="permissions.admin_pvmschool_add &&userInfo.roleType&&(userInfo.roleType.includes(',ARC_MANAGER,') ||userInfo.roleType.includes(',ROLE_ADMIN,'))" size="mini" icon="el-icon-plus" type="primary" @click="addOrUpdateHandle('','add')">新增</el-button>
      </el-button-group>
      <el-form inline :model="dataForm">
        <el-row class="bg-row">
          <el-col :span="6">
            <el-form-item label="学校名称">
              <el-input v-model="dataForm.schoolName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="省名称">
              <el-select filterable default-first-option clearable v-model="dataForm.province" placeholder="请选择" @change="getCitys">
                <el-option v-for="item in provinces" :key="item.id" :label="item.regionName"
                  :value="item.id">
                  <span style="float: left">{{ item.regionName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="市名称">
              <el-select filterable default-first-option clearable v-model="dataForm.city" placeholder="请选择" @change="getAreas">
                <el-option v-for="item in citys" :key="item.id" :label="item.regionName"
                  :value="item.id">
                  <span style="float: left">{{ item.regionName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="区/县名称">
              <el-select filterable default-first-option clearable v-model="dataForm.area" placeholder="请选择">
                <el-option v-for="item in areas" :key="item.id" :label="item.regionName"
                  :value="item.id">
                  <span style="float: left">{{ item.regionName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="bg-row">
          <el-col :span="6">
            <el-form-item label="学校类型">
              <el-select filterable default-first-option clearable v-model="dataForm.schoolType">
                <el-option v-for="(item,index) in typeOptions" :value="item.value" :label="item.label" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="dataList" height="calc(100vh - 215px)" border stripe v-loading="dataListLoading">
          <el-table-column type="index" label="序号" width="40"></el-table-column>
          <el-table-column prop="schoolName" label="学校名称" width="160"></el-table-column>
          <el-table-column prop="province" label="省名称" width="120"></el-table-column>
          <el-table-column prop="city" label="市名称" width="120"></el-table-column>
          <el-table-column prop="area" label="区/县名称" width="120"></el-table-column>
          <el-table-column prop="address" label="详细地址" width="180"></el-table-column>
          <el-table-column prop="fullAddress" label="全地址" min-width="180"></el-table-column>
          <el-table-column prop="schoolType" label="学校类型" min-width="80">
            <template slot-scope="scope">
              <el-tag effect="dark">{{statusFormat(scope.row.schoolType)}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="学校状态" min-width="80">
            <template slot-scope="scope">
              <el-tag effect="dark" v-if="scope.row.status == 1">启用</el-tag>
              <el-tag effect="dark" type="danger" v-if="scope.row.status == -1">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="leader" label="负责人" min-width="80"></el-table-column>
          <el-table-column prop="contactName" label="联系人" min-width="80"></el-table-column>
          <el-table-column prop="contact" label="联系方式" min-width="80"></el-table-column>
          <el-table-column label="操作" width="230" fixed="right">
            <template slot-scope="scope">
              <el-button v-if="userInfo.roleType&&userInfo.roleType.includes(',ROLE_ADMIN,')" type="text" icon="el-icon-edit" @click="syncStudent(scope.row)">同步学生</el-button>
              <el-button v-if="userInfo.roleType&&userInfo.roleType.includes(',ROLE_ADMIN,')" type="text" icon="el-icon-edit" @click="syncCheckData(scope.row)">同步检查</el-button>
              <el-button v-if="permissions.admin_pvmschool_edit &&userInfo.roleType&&(userInfo.roleType.includes(',ARC_MANAGER,') ||userInfo.roleType.includes(',ROLE_ADMIN,'))" type="text" icon="el-icon-edit" @click="addOrUpdateHandle(scope.row.id,'edit')">编辑</el-button>
              <el-button v-if="permissions.admin_pvmschool_del &&userInfo.roleType&&(userInfo.roleType.includes(',ARC_MANAGER,') ||userInfo.roleType.includes(',ROLE_ADMIN,'))" type="text" icon="el-icon-delete" @click="deleteHandle(scope.row)">删除</el-button>
              <el-button v-if="permissions.admin_pvmschool_edit &&userInfo.roleType&&(userInfo.roleType.includes(',ARC_MANAGER,') ||userInfo.roleType.includes(',ROLE_ADMIN,'))" type="text" icon="el-icon-delete" @click="changeStatusHandle(scope.row)">修改状态</el-button>
            </template>
          </el-table-column>

        </el-table>

      <div class="avue-crud__pagination" style="margin-bottom: 25px;">
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100, 200]"
          :page-size="pageSize"
          :total="totalPage"
          background
          layout="total, sizes, prev, pager, next">
        </el-pagination>
      </div>

      <!-- 弹窗, 新增 / 修改 -->
      <table-form v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></table-form>
  </div>
</template>

<script>
  import { filterParams } from '@/util/tools'
  import { remote } from '@/api/admin/dict'
  import { fetchSchoolList, delObj, changeSchoolStatus,syncSchool } from '@/api/pvm/school'
  import { syncStudentInfo } from '@/api/pvm/student'
  import { syncCheckData } from '@/api/pvm/checkdata'
  import { mapGetters } from 'vuex'
  import { getListByParentId } from '@/api/admin/region'

  import TableForm from './TableForm'

  export default {
    name: 'pvmschool',
    data() {
      return {
        dataList: [],
        dataListLoading: false,
        pageIndex: 1,
        pageSize: 100,
        totalPage: 0,
        dataForm: {
          schoolName: '',
          province: '',
          city: '',
          area: ''
        },
        provinces: [],
        citys: [],
        areas: [],
        addOrUpdateVisible: false,
        typeOptions: []
      }
    },
    components: {
      TableForm
    },
    computed: {
      ...mapGetters(['permissions','userInfo'])
    },

    created() {
      this.searchHandle()
      this.getProvinces()
      remote('school_type').then(response => {
        let responseData = response.data.data
        let list = []
        responseData.forEach(item => {
          list.push({label: item.label, value: item.value*1})
        })
        this.typeOptions = [...list]
      })
    },
    methods: {
      //
      searchHandle(){
        this.pageIndex = 1
        this.getDataList()
      },
      clearSearchForm(){
        for(let key in this.dataForm){
          this.dataForm[key] = ''
        }
      },
      addOrUpdateHandle(id,type){
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id,type)
        })

      },
      // 删除
      deleteHandle(row){
        this.$confirm('此操作将永久删除该学校(学校名为:' + row.schoolName + '), 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delObj(row.id)
        }).then(response => {
          if(response.data.code == '0'){
            this.$message.success('删除成功')
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
        syncCheckData(row){
            this.$confirm('此操作将同步学校的检查信息(学校名为:' + row.schoolName + '), 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(function() {
                return syncCheckData(row.id)
            }).then(response => {
              if(response.data.code == '0'){
                this.$message.success('删除成功')
                this.getDataList()
              }else{
                this.$message.error(response.data.msg)
              }
            })
        },
        syncStudent(row){
            this.$confirm('此操作将同步该学校学生信息(学校名为:' + row.schoolName + '), 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(function() {
                return syncStudentInfo(row.id)
            }).then(response => {
              if(response.data.code == '0'){
                this.$message.success('同步学生成功')
                this.getDataList()
              }else{
                this.$message.error(response.data.msg)
              }
            })
        },
      // 修改状态
      changeStatusHandle(row){
        var status = 0;
        if (row.status === 1) {
          status = -1;
        } else {
          status = 1;
        }
        this.$confirm('此操作将永久修改(学校名为:' + row.schoolName + ')的状态，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return changeSchoolStatus(row.id, status);
        }).then(response => {
          if(response.data.code == '0'){
            this.$message.success('修改成功')
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      sizeChangeHandle(val){
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      currentChangeHandle(val){
        this.pageIndex = val
        this.getDataList()
      },
      getDataList(){
        let params1 = {current: this.pageIndex,size: this.pageSize}
        let params2 = filterParams(this.dataForm)
        this.dataListLoading = true
        fetchSchoolList(Object.assign(params1,params2)).then(response => {
          if(response.data.code == '0'){
            this.dataList = response.data.data.records
            this.totalPage = response.data.data.total
          }else{
            this.$message.error(response.data.msg)
          }
          this.dataListLoading = false
        })
      },
      syncSchool(){
        syncSchool().then(response=>{
          if(response.data.code == '0'){
            this.$message.success('同步成功')
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },

      //  转换学校类型
      statusFormat(val){
        let obj = {}
        obj = this.typeOptions.find(item => {
          if(item.value === val){
            return item
          }
        })
        if(obj && obj.label){
          return obj.label
        }
      },
      // 生成省级列表
      getProvinces(){
        var parentId = '86';
        getListByParentId(parentId).then(response => {
          if(response.data.code == '0'){
            this.provinces = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        }).catch(() => {
          alert("省级地址出错了，请联系管理员")
        });
      },
      getCitys(id){
        this.dataForm.city = ''
        this.dataForm.area = ''
        this.citys = []
        this.areas = []
        this.$set(this.dataForm,'city','')
        this.$set(this.dataForm,'area','')
        if(id){
          getListByParentId(id).then(response => {
            if(response.data.code == '0'){
              this.citys = response.data.data
            }else{
              this.$message.error(response.data.msg)
            }
          }).catch(() => {
            alert("省级地址出错了，请联系管理员")
          });
        }
      },
      getAreas(id){
        this.areas = []
        this.$set(this.dataForm,'area','')
        if(id){
          getListByParentId(id).then(response => {
            if(response.data.code == '0'){
              this.areas = response.data.data
            }else{
              this.$message.error(response.data.msg)
            }
          }).catch(() => {
            alert("省级地址出错了，请联系管理员")
          });
        }
      }
    }
  }
</script>
